package com.sitanyun.merchant.guide.frament.view.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseFragment;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.AccountBean;
import com.sitanyun.merchant.guide.bean.MyUserInfoBean;
import com.sitanyun.merchant.guide.bean.ProductsBean;
import com.sitanyun.merchant.guide.bean.SwishShopBean;
import com.sitanyun.merchant.guide.bean.UserInfo;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.MyFPresenterImpl;
import com.sitanyun.merchant.guide.frament.view.activity.BankActivity;
import com.sitanyun.merchant.guide.frament.view.activity.EmployeeActivity;
import com.sitanyun.merchant.guide.frament.view.activity.ProductActivity;
import com.sitanyun.merchant.guide.frament.view.activity.RealNameActivity;
import com.sitanyun.merchant.guide.frament.view.activity.SwitchstoresActivity;
import com.sitanyun.merchant.guide.frament.view.activity.UserMessageActivity;
import com.sitanyun.merchant.guide.frament.view.activity.UserMoneyActivity;
import com.sitanyun.merchant.guide.frament.view.activity.WxImageActivity;
import com.sitanyun.merchant.guide.frament.view.inter.IMyFView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.activity.ForgetPasswordActivity;
import com.sitanyun.merchant.guide.view.activity.LoginActivity;
import com.sitanyun.merchant.guide.weiht.DataCleanManager;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.SPutils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.qcloud.tuicore.TUILogin;
import com.zhy.http.okhttp.OkHttpUtils;

import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends BaseFragment implements IMyFView {


    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.ll_switch)
    LinearLayout llSwitch;
    @BindView(R.id.myall_headImage)
    CircleImageView myallHeadImage;
    @BindView(R.id.myall_name)
    TextView myallName;
    @BindView(R.id.myall_phone)
    TextView myallPhone;
    @BindView(R.id.myall_zx)
    ImageView myallZx;
    @BindView(R.id.tv_audit_list)
    TextView tvAuditList;
    @BindView(R.id.myall_message)
    RelativeLayout myallMessage;
    @BindView(R.id.tv_year_list)
    TextView tvYearList;
    @BindView(R.id.myall_realname)
    LinearLayout myallRealname;
    @BindView(R.id.tv_collection)
    TextView tvCollection;
    @BindView(R.id.myall_bank)
    LinearLayout myallBank;
    @BindView(R.id.tv_change_phone)
    TextView tvChangePhone;
    @BindView(R.id.myall_money)
    LinearLayout myallMoney;
    @BindView(R.id.myall_password)
    LinearLayout myallPassword;
    @BindView(R.id.myall_cache)
    LinearLayout myallCache;
    @BindView(R.id.myall_loginout)
    LinearLayout myallLoginout;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.tv_qh)
    TextView tvQh;
    @BindView(R.id.name_duty)
    TextView nameDuty;
    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.smrz)
    TextView smrz;
    @BindView(R.id.ll_wxmsg)
    LinearLayout llWxmsg;
    @BindView(R.id.wxmsg)
    TextView wxmsg;
    @BindView(R.id.ll_employee)
    LinearLayout llEmployee;
    @BindView(R.id.ll_product)
    LinearLayout llProduct;
    @BindView(R.id.tv_employee)
    TextView tvEmployee;
    @BindView(R.id.tv_employee_num)
    TextView tvEmployeeNum;
    @BindView(R.id.tv_product)
    TextView tvProduct;
    @BindView(R.id.product_num)
    TextView productNum;
    private MyFPresenterImpl mIMyFPresenter;
    private MyUserInfoBean myUserInfoBean;
    private String namesx;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tvTitleStr.setText("我的");
        tvReturn.setVisibility(View.GONE);

    }

    private void initok() {
        OkHttpUtils.get().url(Urls.staffcount)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Bearer" + SharedPreferenceUtil.getStringData("token"))

                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ProductsBean productsBean = new Gson().fromJson(response, ProductsBean.class);
                if (productsBean.getCode()==0){
                    if (productsBean.getData()==0){
                        tvEmployeeNum.setVisibility(View.GONE);
                    }else {
                        tvEmployeeNum.setVisibility(View.VISIBLE);
                        tvEmployeeNum.setText(productsBean.getData()+"人");
                    }

                }
            }
        });
    }

    @Override
    public void initView() {
        mIMyFPresenter = new MyFPresenterImpl(this);
        OkHttpUtils.get().url(Urls.storequery)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Bearer" + SharedPreferenceUtil.getStringData("token"))

                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                SwishShopBean baseEntity = new Gson().fromJson(response, SwishShopBean.class);
                if (baseEntity.getCode()==0){
                    if (baseEntity.getData()!=null){
                        if (baseEntity.getData().size() > 1) {
                            tvQh.setVisibility(View.VISIBLE);
                        } else {
                            tvQh.setVisibility(View.GONE);
                            llSwitch.setClickable(false);
                            tvQh.setClickable(false);
                            tvShop.setClickable(false);
                        }
                    }

                }

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        mIMyFPresenter.getuser();
        if (SharedPreferenceUtil.getStringData("nodeid").equals(SharedPreferenceUtil.getStringData("tonodeid"))){
            llEmployee.setVisibility(View.VISIBLE);
            llProduct.setVisibility(View.VISIBLE);
            tvQh.setText("切换商户");
            initok();
        }else {
            llEmployee.setVisibility(View.GONE);
            llProduct.setVisibility(View.GONE);

        }
    }

    @OnClick({R.id.ll_employee, R.id.ll_product, R.id.ll_switch, R.id.myall_headImage, R.id.myall_zx, R.id.tv_shop, R.id.tv_qh,
            R.id.myall_message, R.id.myall_realname, R.id.myall_bank, R.id.myall_money, R.id.myall_password, R.id.myall_cache, R.id.myall_loginout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //员工
            case R.id.ll_employee:
                startActivity(new Intent(getActivity(), EmployeeActivity.class));
                break;
            //产品
            case R.id.ll_product:
                startActivity(new Intent(getActivity(), ProductActivity.class));
                break;
            //切换门店
            case R.id.ll_switch:
            case R.id.tv_shop:
            case R.id.tv_qh:
                if (DateUtils.isFastClick()) {
                    return;
                }
                startActivity(new Intent(getActivity(), SwitchstoresActivity.class));
                break;

            case R.id.myall_headImage:

                break;
            //erweima
            case R.id.myall_zx:
                if (DateUtils.isFastClick()) {
                    return;
                }
                if (myUserInfoBean.getData().getWxEwm() == null) {
                    startActivity(new Intent(getActivity(), WxImageActivity.class)
                            .putExtra("wximg", "null"));
                }
                break;
            //我的消息
            case R.id.myall_message:
                if (DateUtils.isFastClick()) {
                    return;
                }
                startActivity(new Intent(getActivity(), UserMessageActivity.class));
                break;
            //实名
            case R.id.myall_realname:
                if (DateUtils.isFastClick()) {
                    return;
                }
                startActivity(new Intent(getActivity(), RealNameActivity.class).putExtra("name", myUserInfoBean.getData().getName() + "")
                        .putExtra("isIndividual", myUserInfoBean.getData().getIsIndividual() + ""));
                break;
            //银行卡
            case R.id.myall_bank:
                if (DateUtils.isFastClick()) {
                    return;
                }
                if (myUserInfoBean.getData().getIsIndividual() == 0) {
                    dialog();
                    return;
                } else {
                    startActivity(new Intent(getActivity(), BankActivity.class)
                            .putExtra("isIndividual", myUserInfoBean.getData().getIndividualId() + ""));
                }

                break;
            //钱包
            case R.id.myall_money:
                if (DateUtils.isFastClick()) {
                    return;
                }
                if (myUserInfoBean.getData().getIsIndividual() == 1) {
                    SharedPreferenceUtil.SaveData("isindividuals", "1");

                } else {
                    SharedPreferenceUtil.SaveData("isindividuals", "0");
                }

                startActivity(new Intent(getActivity(), UserMoneyActivity.class)
                        .putExtra("name", myUserInfoBean.getData().getName() + "")
                        .putExtra("iscard", myUserInfoBean.getData().getIsCard() + "")
                        .putExtra("isIndividual", myUserInfoBean.getData().getIndividualId() + ""));

                break;
            ///修改密码
            case R.id.myall_password:
                if (DateUtils.isFastClick()) {
                    return;
                }
                startActivity(new Intent(getActivity(), ForgetPasswordActivity.class));

                break;
            //缓存
            case R.id.myall_cache:
                if (DateUtils.isFastClick()) {
                    return;
                }
                try {
                    String totalCacheSize = DataCleanManager.getTotalCacheSize(getActivity());
                    DataCleanManager.clearAllCache(getActivity());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            //退出登录
            case R.id.myall_loginout:
                if (DateUtils.isFastClick()) {
                    return;
                }
                dialogout();
                break;
        }
    }

    //退出登录
    private void dialogout() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getActivity(), R.layout.loginoutdialog_item, null);
        dialog.setContentView(view);
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.define).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (SharedPreferenceUtil.getStringData("nodeid").equals(SharedPreferenceUtil.getStringData("tonodeid"))){
                    OkHttpUtils.delete().url(Urls.logout)
                            .addHeader("Content-Type", "application/x-www-form-urlencoded")
                            .addHeader("Authorization", "Bearer" + SharedPreferenceUtil.getStringData("token"))
                            .build().execute(new StringCallbacks() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            AccountBean accountBean = new Gson().fromJson(response, AccountBean.class);
                            if (accountBean.getCode() == 0) {
                                //清除IM
                                TUILogin.logout(new V2TIMCallback() {
                                    @Override
                                    public void onSuccess() {
                                        UserInfo.getInstance().setToken("");
                                        UserInfo.getInstance().setAutoLogin(false);
                                    }

                                    @Override
                                    public void onError(int i, String s) {

                                    }
                                });

                                //退出清除本地
                                SharedPreferenceUtil.clearAll();
                                SPutils.clearAll();
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                getActivity().finish();
                                dialog.dismiss();
                            }
                        }
                    });
                }else {

                    OkHttpUtils.delete().url(Urls.forcelogout)
                            .addHeader("Content-Type", "application/x-www-form-urlencoded")
                            .addHeader("Authorization", "Bearer" + SharedPreferenceUtil.getStringData("token"))
                            .build().execute(new StringCallbacks() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            AccountBean accountBean = new Gson().fromJson(response, AccountBean.class);
                            if (accountBean.getCode() == 0) {
                                //清除IM
                                TUILogin.logout(new V2TIMCallback() {
                                    @Override
                                    public void onSuccess() {
                                        UserInfo.getInstance().setToken("");
                                        UserInfo.getInstance().setAutoLogin(false);
                                    }

                                    @Override
                                    public void onError(int i, String s) {

                                    }
                                });

                                //退出清除本地
                                SharedPreferenceUtil.clearAll();
                                SPutils.clearAll();
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                getActivity().finish();
                                dialog.dismiss();
                            }
                        }
                    });
                }



            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);

    }

    //弹窗
    private void dialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getActivity(), R.layout.item_banks, null);
        dialog.setContentView(view);
        view.findViewById(R.id.qx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.qrz).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), RealNameActivity.class).putExtra("name", myUserInfoBean.getData().getName() + "").putExtra("isIndividual", myUserInfoBean.getData().getIsIndividual() + ""));
                dialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);

    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IMyFView.RESPONSE_ONE) {
            myUserInfoBean = (MyUserInfoBean) response;
            if (myUserInfoBean.getCode() == 0) {

                if (myUserInfoBean.getData().getWxEwmId() == null) {
                    wxmsg.setVisibility(View.VISIBLE);
                    llWxmsg.setVisibility(View.VISIBLE);
                } else {

                    wxmsg.setVisibility(View.GONE);
                    llWxmsg.setVisibility(View.GONE);
                }
                 if (myUserInfoBean.getData().getSenceCount().getSoonCount()==0){
                     String num="";
                     productNum.setText(myUserInfoBean.getData().getSenceCount().getCount()+"个产品许可"+num);
                 }else {
                     String num=myUserInfoBean.getData().getSenceCount().getSoonCount()+"个即将过期";
                     productNum.setText(myUserInfoBean.getData().getSenceCount().getCount()+"个产品许可,"+num);
                 }

                SharedPreferenceUtil.SaveData("sfz", myUserInfoBean.getData().getIdNum() + "");
                SharedPreferenceUtil.SaveData("individ", myUserInfoBean.getData().getIndividualId() + "");
                SharedPreferenceUtil.SaveData("phone", myUserInfoBean.getData().getPhone() + "");

                if (myUserInfoBean.getData().getStroe()==null){
                    tvShop.setVisibility(View.GONE);
                }else {
                    tvShop.setText(myUserInfoBean.getData().getStroe() + "");
                }
                nameDuty.setText(myUserInfoBean.getData().getPosition() + "");

                if (myUserInfoBean.getData().getIsIndividual() == 0) {
                    smrz.setVisibility(View.VISIBLE);
                } else {
                    /**
                     * 已经实名
                     */
                    String strs = "";
                    String names = myUserInfoBean.getData().getRealname();
                    String str = names.substring(names.length() - 1);
                    if (names.length() >= 3) {
                        strs = names.substring(0, 1);
                    } else {
                        strs = "";
                    }
                    for (int i = 1; i < names.length(); i++) {
                        if (i == 1) {
                            namesx = names.replaceAll(names, "*");
                        } else if (i == 2) {
                            namesx = names.replaceAll(names, "*");
                        } else {
                            namesx = names.replaceAll(names, "*");
                        }
                    }
                    String name = strs + namesx + str;
                    smrz.setTextColor(getResources().getColor(R.color.shop));
                    smrz.setText(name);
                }
                Glide.with(getActivity()).load(myUserInfoBean.getData()
                        .getHeadUrl()).apply(new RequestOptions().error(R.mipmap.cimg)).into(myallHeadImage);
                myallName.setText(myUserInfoBean.getData().getName() + "");
                myallPhone.setText(myUserInfoBean.getData().getPhone() + "");
                Glide.with(getActivity()).load(myUserInfoBean.getData()
                        .getWxEwm()).apply(new RequestOptions().error(R.mipmap.zx)).into(myallZx);
            } else {
                ToastUtil.showToast(getActivity(), myUserInfoBean.getMsg() + "");
            }
        }
    }


}
